package com.lwm.springcloud.controller;

import cn.hutool.core.util.ObjectUtil;
import com.lwm.springcloud.entity.MsgInfo;
import com.lwm.springcloud.entity.Payment;
import com.lwm.springcloud.lb.LoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author lwmzzz
 * @version 1.0
 * @date 2020/11/24 0:11
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/consumer/")
public class OderController {
//    public static final String PAYMENT_URL = "http://localhost:8001";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private LoadBalance loadBalance;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/payment/c")
    public MsgInfo<Payment> createPayment(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/c", payment, MsgInfo.class);
    }

    @GetMapping("/payment/r/{id}")
    public MsgInfo<Payment> getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/r/" + id, MsgInfo.class);
    }

    @GetMapping("/payment/r1/{id}")
    public MsgInfo<Payment> getPayment2(@PathVariable("id") Long id) {
        ResponseEntity<MsgInfo> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/r/" + id, MsgInfo.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            log.info("请求成功，返回请求头信息：{}", entity.getStatusCode() + "\t" + entity.getHeaders());
            return entity.getBody();
        } else {
            return new MsgInfo(444, "操作失败");
        }
    }

    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (ObjectUtil.isEmpty(instances)) {
            log.error("instances为空，或者size = 0,参数：{}", "CLOUD-PAYMENT-SERVICE");
            return null;
        }
        ServiceInstance serviceInstance = loadBalance.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }
}
